package main.Daoimpl;

/**
 * 作者: ALIM-MASTIK
 * 创建实现: 2023/7/14 21:35
 * 项目名称：chat
 * 软件: IntelliJ IDEA
 */
import main.JdbcUtils;
import main.dao.ChatRoomDAO;
import main.pojo.ChatRoom;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class ChatRoomDAOImpl implements ChatRoomDAO {
    private Connection connection= JdbcUtils.getConnection();
    private QueryRunner queryRunner=new QueryRunner();

    // 构造方法

    public ChatRoomDAOImpl(Connection connection) {
        this.connection = connection;
        this.queryRunner = new QueryRunner();
    }

    // 实现接口方法

    @Override
    public ChatRoom getChatRoomByID(int chatRoomID){
        String query = "SELECT * FROM chatrooms WHERE ChatRoomID = ?";
        try {
            return queryRunner.query(connection, query, new BeanHandler<>(ChatRoom.class), chatRoomID);
        } catch (SQLException e) {
            return null;
        }
    }

    @Override
    public List<ChatRoom> getAllChatRooms()  {
        String query = "SELECT * FROM chatrooms";
        try {
            return queryRunner.query(connection, query, new BeanListHandler<>(ChatRoom.class));
        } catch (SQLException e) {
            return null;
        }
    }

    @Override
    public Boolean createChatRoom(ChatRoom chatRoom) {
        String query = "INSERT INTO chatrooms (ChatRoomID, ChatRoomName) VALUES (?, ?)";
        try {
            queryRunner.update(connection, query, chatRoom.getChatRoomID(), chatRoom.getChatRoomName());
            return true;
        } catch (SQLException e) {
            return false;
        }
    }

    @Override
    public Boolean updateChatRoom(ChatRoom chatRoom)  {
        String query = "UPDATE chatrooms SET ChatRoomName = ? WHERE ChatRoomID = ?";
        try {
            queryRunner.update(connection, query, chatRoom.getChatRoomName(), chatRoom.getChatRoomID());
            return true;
        } catch (SQLException e) {
            return false;
        }
    }
    @Override
    public Boolean deleteChatRoom(int chatRoomID)  {
        String query = "DELETE FROM chatrooms WHERE ChatRoomID = ?";
        try {
            queryRunner.update(connection, query, chatRoomID);
            return true;
        } catch (SQLException e) {
            return false;
        }
    }

    // 关闭数据库连接
    public void closeConnection() {
        DbUtils.closeQuietly(connection);
    }
}
